﻿using AutoMapper;
using ERP.Inventory.Api.Write.Application.Command.库存管理;
using ERP.Inventory.Domain.库存管理;
using ERP.Inventory.Errorcode;
using ERP.Inventory.Infastructure.Interface;
using MediatR;

namespace ERP.Inventory.Api.Write.Application.Handler.库存管理
{
    public class CheckShopCreateHandler : IRequestHandler<CheckShopCreateCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<CheckandShopModel> checkshopRepo;
        private readonly IBaseRepository<ShopModel> shopRepo;
        private readonly IBaseRepository<CheckModel> checkRepo;
        private readonly IMapper mapper;

        public CheckShopCreateHandler(IBaseRepository<CheckandShopModel> checkshopRepo, IBaseRepository<ShopModel> shopRepo, IBaseRepository<CheckModel> checkRepo, IMapper mapper)
        {
            this.checkshopRepo = checkshopRepo;
            this.shopRepo = shopRepo;
            this.checkRepo = checkRepo;
            this.mapper = mapper;
        }
        public async Task<ApiResult<int>> Handle(CheckShopCreateCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<int>();
            List<int> idList = new List<int>();
            
            try
            {
                idList = request.Ids.Split(',').Select(x => Convert.ToInt32(x)).ToList();
            }
            catch (FormatException)
            {
                res.Message = "ids参数格式不正确，请提供逗号分隔的整数列表";
                res.Code = ApiEnum.Error;
                return res;
            }

            // 先查询并更新盘点记录
            //var model = checkRepo.GetAll().FirstOrDefault(x => x.InvenCode == request.InvenCode);
            //if (model == null)
            //{
            //    res.Message = "未找到对应的盘点记录";
            //    res.Code = ApiEnum.Error;
            //    return res;
            //}
            
            //model.IsHaveShop = true;
            //await checkRepo.Update(model);
            
            // 创建CheckandShopModel列表
            List<CheckandShopModel> list = new List<CheckandShopModel>();
            foreach (var id in idList)
            {
                CheckandShopModel checkandShopModel = new CheckandShopModel
                {
                    InvenId = request.InvenId,
                    ShopId = id
                };
                list.Add(checkandShopModel);
            }
            
            // 使用批量添加方法
            int addResult = await checkshopRepo.AddRange(list);
            
            if (addResult > 0)
            {
                res.Message = $"成功新增{list.Count}条记录";
                res.Code = ApiEnum.Ok;
                res.Data = list.Count;
            }
            else
            {
                res.Message = "新增失败";
                res.Code = ApiEnum.Error;
                res.Data = 0;
            }
            
            return res;
        }
    }
}
